package httpHandle

import (
	"github.com/gin-gonic/gin"
	"github.com/wzh200x/webServer/constants"
	"github.com/wzh200x/webServer/httpHandle/service"
	"github.com/wzh200x/webServer/middleware/auth"
	"github.com/wzh200x/webServer/middleware/response"
)

// 使用service包中定义的请求和响应结构
type CreateCharacterRequest service.CreateCharacterRequest
type UpdateCharacterRequest service.UpdateCharacterRequest
type CharacterResponse service.CharacterResponse

// HandleCreateCharacter 处理创建角色请求
func HandleCreateCharacter(c *gin.Context) {
	success, err := response.GetResponseFuncs(c)

	// 从上下文中获取用户信息
	userID, username := auth.GetCurrentUser(c)

	// 解析请求参数
	var req CreateCharacterRequest
	if bindErr := c.ShouldBind(&req); bindErr != nil {
		err(constants.ErrUnknown, "无效的请求参数")
		return
	}

	// 转换为service层的请求结构
	serviceReq := service.CreateCharacterRequest{
		Name:     req.Name,
		Data:     req.Data,
		ServerID: req.ServerID,
	}

	// 调用service层创建角色
	character, errCode, errMsg := service.CreateCharacter(userID, username, serviceReq)
	if errCode > 0 {
		err(errCode, errMsg)
		return
	}

	// 返回角色信息
	success(character)
}

// HandleGetCharacter 处理获取角色请求
func HandleGetCharacter(c *gin.Context) {
	success, err := response.GetResponseFuncs(c)

	// 从上下文中获取用户信息
	userID, username := auth.GetCurrentUser(c)

	// 调用service层获取角色
	character, errCode, errMsg := service.GetCharacter(userID, username)
	if errCode > 0 {
		err(errCode, errMsg)
		return
	}

	// 返回角色信息
	success(character)
}

// HandleUpdateCharacter 处理修改角色数据请求
func HandleUpdateCharacter(c *gin.Context) {
	success, err := response.GetResponseFuncs(c)

	// 从上下文中获取用户信息
	userID, username := auth.GetCurrentUser(c)

	// 解析请求参数
	var req UpdateCharacterRequest
	if bindErr := c.ShouldBind(&req); bindErr != nil {
		err(constants.ErrUnknown, "无效的请求参数")
		return
	}

	// 转换为service层的请求结构
	serviceReq := service.UpdateCharacterRequest{
		Data: req.Data,
	}

	// 调用service层更新角色
	character, errCode, errMsg := service.UpdateCharacter(userID, username, serviceReq)
	if errCode > 0 {
		err(errCode, errMsg)
		return
	}

	// 返回更新后的角色信息
	success(character)
}
